
package com.augurit.gzcgwsp.common.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;

/**
 * <p>Title: 文件下载</p>
 * <p>Description:文件下载 </p>
 * <p>Copyright: Copyright (c) 2012</p>
 * <p>Company: augurit</p>
 * @author zj
 * @version 1.0
 * @descript 
 */
public class DownLoadFile {
	protected HttpServletRequest m_request;

	protected HttpServletResponse m_response;

	protected ServletContext m_application;

	private String m_contentDisposition;

	public DownLoadFile() {
	}

	public final void initialize(PageContext pagecontext) {
		m_application = pagecontext.getServletContext();
		m_request = (HttpServletRequest) pagecontext.getRequest();
		m_response = (HttpServletResponse) pagecontext.getResponse();
	}

	public void downloadFile(String strFilePath, String strName)
			throws ServletException, IOException {
		downloadFile(strFilePath, strName, null, null);
	}

	public void downloadFile(String strFilePath, String strName,
			String strContentType) throws ServletException, IOException {
		downloadFile(strFilePath, strName, strContentType, null);
	}

	public void downloadFile(String strFilePath, String strFileName,
			String strContentType, String strDisp) throws ServletException,
			IOException {
		downloadFile(strFilePath, strFileName, strContentType, strDisp, 8192);
	}

	/**
	 * 判断文件是否存在
	 * @param strFileName
	 *            
	 * @return 

	 * 
	 */
	private boolean isVirtual(String strFileName) {
		if (m_application.getRealPath(strFileName) != null) {
			File file = new File(m_application.getRealPath(strFileName));
			return file.exists();
		} else {
			return false;
		}
	}

	/**
	 * 开始下载文件
	 * @param strFilePath
	 * @param strFileName
	 * @param strContentType
	 * @param strDisp
	 * @param btLen
	 * @throws ServletException
	 * @throws IOException
	 */

	public void downloadFile(String strFilePath, String strFileName,
			String strContentType, String strDisp, int btLen)
			throws ServletException, IOException {

		if (strFilePath == null)
			throw new IllegalArgumentException("File '" + strFilePath
					+ "' not found (1040).");
		if (strFilePath.equals(""))
			throw new IllegalArgumentException("File '" + strFilePath
					+ "' not found (1040).");
		//String filepath=new String(strFilePath.getBytes("ISO-8859-1"),"utf-8");
		boolean flag=isVirtual(strFilePath);
		if (flag) {
			strFilePath = m_application.getRealPath(strFilePath);
		}

		// System.out.println("----filepath----------***-----" + strFilePath);
		// System.out.println("----strFileName-------****----" + strFileName);
		FileInputStream fileinputstream = null;
		OutputStream out = null;
		try {
			File file = new File(strFilePath);
			fileinputstream = new FileInputStream(file);
			long lngSize = file.length();
			byte abyte0[] = new byte[btLen];
			// 设置文件编码
			if (strContentType == null)
				m_response
						.setContentType("application/octet-stream;charset=UTF-8");
			else if (strContentType.length() == 0)
				m_response
						.setContentType("application/octet-stream;charset=UTF-8");
			else
				m_response.setContentType(strContentType);

			m_response.setContentLength((int) lngSize);

			m_contentDisposition = m_contentDisposition != null ? m_contentDisposition
					: "attachment;";
			if (strDisp == null) {
				if (strFileName == null)
					strFileName = "";

				if (strFileName.equals("")) {
					strFileName = this.getFileName(strFilePath);
				} else {
					strFileName = this.getFileName(strFileName);
				}
				String strFile2 = URLEncoder.encode(strFileName, "utf-8");
				m_response.setHeader("Content-Disposition",
						m_contentDisposition + " filename=" + strFile2);
			} else if (strDisp.length() == 0) {
				m_response.setHeader("Content-Disposition",
						m_contentDisposition);
			} else {
				m_response.setHeader("Content-Disposition",
						m_contentDisposition + " filename=" + strDisp);
			}
			int j;
			m_response.setBufferSize((int) file.length());
			out = m_response.getOutputStream();

			while ((j = fileinputstream.read(abyte0, 0, btLen)) != -1) {
				out.write(abyte0, 0, j);
			}
		} catch (Exception e) {
			e.printStackTrace();
			m_request.setCharacterEncoding("GBK");
			m_response
					.getWriter()
					.print(
							"<SCRIPT LANGUAGE=\"JavaScript\"> alert(\"文件不存在!\");</SCRIPT>");
		} finally {
			fileinputstream.close();
			out.flush();
			fileinputstream.close();
			out.close();
		}

	}

	/**
	 * 获取文件名称
	 * @param strFileName
	 * @return
	 */
	private String getFileName(String strFileName) {
		int iPos = 0;
		iPos = strFileName.lastIndexOf('/');
		if (iPos != -1)
			return strFileName.substring(iPos + 1, strFileName.length());
		iPos = strFileName.lastIndexOf('\\');
		if (iPos != -1)
			return strFileName.substring(iPos + 1, strFileName.length());
		else
			return strFileName;
	}

}
